/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package builder;

import utils.Debug;
import utils.Utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 *
 * @author daz
 */
public class DatBuilder {

    private String desPath = "";

    public void setDesPath(String desPath) {
        this.desPath = desPath;
    }
    private String folderPath = "E:/BGATE/DATATOOLCBR/";

    public void setFolderPath(String folderPath) {
        this.folderPath = folderPath + File.separator;
    }

    public void creatDatFile(String data, String id) {
//        PrintWriter pw = null;

        try {
            FileOutputStream outputStream = null;
            Debug.d("desPath :" + desPath);
            if (desPath.length() == 0) {
                outputStream = new FileOutputStream(folderPath + "info.dat");
            } else {
                File folder = new File(desPath);
                if (!folder.exists()) {
                    boolean result = folder.mkdirs() || folder.mkdir();
                    Debug.d("make folder");

                }
                outputStream = new FileOutputStream(desPath + "info.dat");
            }
            Debug.d("data :" + data);
            outputStream.write(generateData(MD5(data), Integer.parseInt(id)));
            outputStream.close();
//            File datFile = new File(folderPath + "info.dat");
//            if (datFile.exists()) {
//                datFile.delete();
//            }
//            pw = new PrintWriter(new BufferedWriter(new FileWriter(datFile)));
//            pw.
//            pw.println(dataEncryted);
//            pw.flush();
//            pw.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
//            pw.close();
        }
    }

    private byte[] generateData(String data, int id) {
        int startPos = Utils.nextInt(8);
        int dataLength = data.length();
        byte[] buffer = new byte[dataLength];
        byte[] posByteData = Utils.intToByteArray(startPos);
        byte[] idByteData = Utils.intToByteArray(id);
        System.arraycopy(posByteData, 0, buffer, dataLength - 5, 4);
        System.arraycopy(idByteData, 0, buffer, startPos, 4);
        return buffer;
    }

    public static String MD5(String md5) {
        try {
            Debug.d("md5 :" + md5);
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(md5.getBytes());
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
        }
        return null;
    }
}
